package com.rc.evcharger.controller;

import com.rc.evcharger.common.base.TResponse;
import com.rc.evcharger.common.constant.CommonConstant;
import com.rc.evcharger.common.utils.BeanUtil;
import com.rc.evcharger.common.utils.log.SelChargeProcessLogUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Create by Yang on 2021/4/21
 */

@RestController
@RequestMapping("/log")
public class ChargeProcessLogController {

    //查询的日志文件路径
    final String filePath = "/var/wwwlog/rc-evcharger/";

    //临时存数据的文件
    final String tempFileName = "/var/tempChargeProcess.txt";
    //final String tempFileName = "D:\\var\\tempChargeProcess.txt";

    @RequestMapping(value = "/selectChargeProcess", method = RequestMethod.GET)
    @ResponseBody
    public Object selectChargeProcess(String fileName, String orderNum, HttpServletResponse response) throws Exception {
        if (!BeanUtil.isValid(fileName, orderNum)) {
            TResponse.FAIL("参数为空");
        }
        response.reset();// 不加这一句的话会出现下载错误

        response.setHeader("Content-disposition", "attachment; filename=" + orderNum + ".txt");// 设定输出文件头
        //response.setContentType("text/x-plain");// 定义输出类型


        ServletOutputStream out = response.getOutputStream();

        File tempFile = new File(tempFileName);
        FileOutputStream fos = new FileOutputStream(tempFile);
        Writer writer = new OutputStreamWriter(fos, "utf-8");

        String text = SelChargeProcessLogUtil.getSelReport(filePath + fileName, orderNum, tempFileName);
        writer.write(text);
        writer.close();
        fos.close();

        FileInputStream fis = new FileInputStream(tempFile);
        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(4096);

        byte[] cache = new byte[4096];
        for (int offset = fis.read(cache); offset != -1; offset = fis.read(cache)) {
            byteOutputStream.write(cache, 0, offset);
        }

        byte[] bt = null;
        bt = byteOutputStream.toByteArray();

        out.write(bt);
        out.flush();
        out.close();
        fis.close();
        if (tempFile.exists()) {
            tempFile.delete();
        }

        return TResponse.SUCCESS(CommonConstant.MSG_SUCCESS);
    }
}
